package com.sm.chatinputlibrary;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.RectF;
import androidx.annotation.Nullable;
import android.util.AttributeSet;
import android.view.View;

import com.scorpio.baselibrary.ScreenAdapterTools;

/**
 * created by zhud on 2019/4/12
 */
public class AudioProgressView extends View {
    private final int mPlayMaxAudiovolume = 10;
    private int mPlayAudiovolume = 0;
    private Paint mPaint;
    private int progress_height = 9;
    private int progress_height_interval = 7;
    private int progress_init_width = 31;
    private int progress_width_interval = 7;
    //上一次刷新时间
    private long lastTime = System.currentTimeMillis();

    public AudioProgressView(Context context) {
        this(context, null);
    }

    public AudioProgressView(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public AudioProgressView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        progress_height = ScreenAdapterTools.getInstance().loadCustomAttrValue(progress_height);
        progress_height_interval = progress_height + ScreenAdapterTools.getInstance().loadCustomAttrValue(progress_height_interval);
        progress_init_width = ScreenAdapterTools.getInstance().loadCustomAttrValue(progress_init_width);
        progress_width_interval = ScreenAdapterTools.getInstance().loadCustomAttrValue(progress_width_interval);
        initPaint();
    }

    private void initPaint() {
        mPaint = new Paint();
        mPaint.setColor(Color.WHITE);
        mPaint.setStyle(Paint.Style.FILL);
        mPaint.setStrokeWidth(3);
        mPaint.setAntiAlias(true);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        int bottom = getHeight();
        RectF rectF = new RectF();
        if (mPlayAudiovolume > mPlayMaxAudiovolume) mPlayAudiovolume = mPlayMaxAudiovolume;
        if (mPlayAudiovolume > 0) {
            for (int i = 0; i < mPlayAudiovolume; i++) {
                rectF.left = 0;
                rectF.top = bottom - progress_height_interval * i - progress_height;
                rectF.right = rectF.left + progress_init_width + progress_width_interval * i;
                rectF.bottom = rectF.top + progress_height;
                canvas.drawRoundRect(rectF, 5, 5, mPaint);
            }
        }
    }

    public void setPlayAudiovolume(int playAudiovolume) {
        this.mPlayAudiovolume = playAudiovolume;
        //放置连续刷新
        if (System.currentTimeMillis() - lastTime > 1000 / 10) {
            postInvalidate();
            lastTime = System.currentTimeMillis();
        }
    }

}
